import requests
import time
import random
import sys
from loguru import logger
import json

headers = {
        "Content-Type": "application/json"
    }
clientKey = "1306454c1e434335bda6b74251c27338592999"

def createTask():
    url = "https://api.ez-captcha.com/createTask"
    payload = json.dumps({
        "clientKey": clientKey,
        "task": {
            "websiteURL": "https://online.seranking.com/login.html?back=true&do=login",
            "websiteKey": "6Lejfp8pAAAAAJrnJ4-oIeKBkb0KmGt_5VKgEGO_",
            "type": "ReCaptchaV2TaskProxyless",
            "isInvisible": False
        }
    })
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.post(url, headers=headers, data=payload, timeout=5)
        except Exception as e:
            # logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        data = res.json()
        if data['errorId'] == 0:
            logger.info(f"提交成功： {data['taskId']}")
            return data['taskId']
        else:
            sys.exit()

def getTaskResult():
    taskId = createTask()
    url = "https://api.ez-captcha.com/getTaskResult"
    payload = json.dumps({
        "clientKey": clientKey,
        "taskId": str(taskId)
    })
    time_sleep = 0
    while time_sleep < 150:
        res = requests.post(url, headers=headers, data=payload)
        data = res.json()
        if data['status'] == "ready":
            print(data['solution']['gRecaptchaResponse'])
            return data['solution']['gRecaptchaResponse']
        else:
            logger.info(f"等待中, 请稍后")
            time_sleep += 5
            time.sleep(5)

# if __name__ == '__main__':
#     getTaskResult()